package bold.shiro;


import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.apache.shiro.web.servlet.AdviceFilter;
import org.apache.shiro.web.servlet.ShiroHttpServletRequest;
import org.apache.shiro.web.session.mgt.DefaultWebSessionManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.Serializable;

/**
 * shiro 认证过滤
 * 没登录的情况下 异常拦截器拦截不到，所有在这里处理
 */
@Slf4j
public class MyAuthFilter extends AdviceFilter {

    private MySessionManager sessionManager;

    public MyAuthFilter(MySessionManager sessionManager) {
        this.sessionManager = sessionManager;
    }


    @Override
    protected boolean preHandle(ServletRequest request, ServletResponse response) {

        Serializable sessionId = sessionManager.getSessionId(request, response);
        if (sessionId == null) {
            log.info("shiro-trace-没token=获取资源={}", ((ShiroHttpServletRequest) request).getServletPath());
            writeResponse(response, "没token");//无权限情况shiro自己处理
            return false;
        }

        HttpServletRequest servletRequest = (HttpServletRequest) request;
        HttpSession session = servletRequest.getSession(false);
        if (session == null) {
            log.info("shiro-trace-登陆过期=获取资源={}", ((ShiroHttpServletRequest) request).getServletPath());
            writeResponse(response, "登陆过期");
            return false;
        }

        //无权限情况shiro自己处理 todo
        log.info("shiro-trace-已经登陆");
        return true;
    }

    private void writeResponse(ServletResponse response, String msg) {
        PrintWriter out = null;
        try {
            response.setContentType("application/json;charset=UTF-8");
            out = response.getWriter();
            out.print(msg);
            out.flush();

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (out != null) {
                out.close();
            }
        }
    }

}